package com.javen.controller;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.javen.model.Food;
import com.javen.model.Order;
import com.javen.model.Seller;
import com.javen.service.UserService;
  
  
@Controller  
@RequestMapping("/user")  

public class UserController {  
	private static Logger log=LoggerFactory.getLogger(UserController.class);
	 @Resource  
	 private UserService userService;      
	 
	 /**
	  * 获取所有商家
	 * @return Map<String,Object>
	 */
	@ResponseBody
	 @RequestMapping(value="/sellers",method=RequestMethod.GET)
	 public Map<String,Object> getSellers(){
		 Map<String,Object> map = new HashMap<String, Object>();
		 List<Seller> sellers = userService.getSellers();
		 map.put("sellers", sellers);
		 
		 return map;
	 }
	 
	 /**
	  * 获取商家的所有菜
	 * @param sellerId
	 * @return Map<String,Object>
	 */
	@ResponseBody
	@RequestMapping(value="/seller/{sellerId}",method=RequestMethod.GET)
	public Map<String,Object> getSeller(@PathVariable("sellerId") int sellerId){
	     Map<String,Object> map = new HashMap<String, Object>();
	     Seller seller = userService.getSeller(sellerId);
	     List<Food> foods = userService.getFoods(sellerId);
	     
	     map.put("seller", seller);	 
	     map.put("foods", foods);
	     
	     return map;
	}
	/**
	  * 获取商家的所有菜
	 * @param sellerId
	 * @return Map<String,Object>
	 * @throws UnsupportedEncodingException 
	 */
	@ResponseBody
	@RequestMapping(value="/foods",method=RequestMethod.GET)
	public Map<String,Object> getFoods(int sellerId,String className){
		
		switch(className) {
		case "a" : {className = "主菜";break;}
		case "b" : {className = "老火靓汤";break;}
		case "c" : {className = "饮料";break;}
		}
		
	    Map<String,Object> map = new HashMap<String, Object>();	     
	    List<Food> foods = userService.getFoodsByClassName(sellerId,className);
	    
	    map.put("foods", foods);
	    
	    return map;
	}
	/**
	 * 向购物车里添加商品
	 * @param request
	 * @param response
	 * @param foodId_
	 * @return Map<String,Object>
	 */
	@ResponseBody
	@RequestMapping(value = "/plusFood/{foodId}",method = RequestMethod.POST)
	public Map<String,Object> plusFood(HttpServletRequest request,HttpServletResponse response, @PathVariable("foodId") int foodId_){
		Map<String,Object> map = new HashMap<String, Object>();
		Cookie[] cookies = request.getCookies();
		String foodId = String.valueOf(foodId_);
		boolean judge = false;
		
		if(cookies == null) {
			Cookie cookie = new Cookie(foodId, "1");
			cookie.setPath("/");			//必须配置路径，否则另一个方法不能获取到相同的cookie
			response.addCookie(cookie);     
			log.info("cookies == null");
		}
		else {
			for(int i = 0;i < cookies.length;i++) {
				log.info(cookies[i].getName());
				if(cookies[i].getName().equals(foodId)) {
					int sum = Integer.valueOf(cookies[i].getValue());
					++sum;
					cookies[i].setValue(String.valueOf(sum));
					judge = true;
					cookies[i].setPath("/");
					response.addCookie(cookies[i]);      //覆盖原先的cookie即修改cookie
					log.info(cookies[i].getName() + sum);
				}
				
			}
			if(judge == false) {
				Cookie cookie = new Cookie(foodId, "1");
				cookie.setPath("/");
				response.addCookie(cookie);
			}
		}
		map.put("result", 1);
		return map;
	}
	/**
	 * 向购物车里减少商品
	 * @param request
	 * @param response
	 * @param foodId_
	 * @return Map<String,Object>
	 */
	@ResponseBody
	@RequestMapping(value = "/minusFood/{foodId}",method = RequestMethod.POST)
	public Map<String,Object> minusFood(HttpServletRequest request,HttpServletResponse response, @PathVariable("foodId") int foodId_){
		Map<String,Object> map = new HashMap<String, Object>();
		Cookie[] cookies = request.getCookies();
		String foodId = String.valueOf(foodId_);
		System.out.println("minusFood");
		if(cookies == null) System.out.println("cookies == null");
		else {
			for(int i = 0;i < cookies.length;i++) {
				System.out.println(cookies[i].getName());
				if(cookies[i].getName().equals(foodId)) {
					int sum = Integer.valueOf(cookies[i].getValue());
					if(sum <= 0) {
						cookies[i].setValue("0");
						cookies[i].setPath("/");        //必须配置路径，否则另一个方法不能获取到相同的cookie
						response.addCookie(cookies[i]);
						System.out.println(cookies[i].getName() + sum);
					}
					else {
					--sum;
					cookies[i].setValue(String.valueOf(sum));
					cookies[i].setPath("/");
					response.addCookie(cookies[i]);
					System.out.println(cookies[i].getName() + sum);
					}
				}
			}
		}
		map.put("result", 1);
		return map;
	}
	/**
	 * 展示购物车
	 * @param request
	 * @param response
	 * @param sellerId
	 * @return Map<String,Object>
	 */
	@ResponseBody
	@RequestMapping(value = "/shoppingCart/{sellerId}",method = RequestMethod.GET)
	public Map<String,Object> shoppingCart(HttpServletRequest request,HttpServletResponse response,@PathVariable("sellerId") int sellerId){
		Map<String,Object> map = new HashMap<String, Object>();
		Cookie[] cookies = request.getCookies();
		List<Food> foods = new ArrayList<Food>(); 
		System.out.println(sellerId);
		Seller seller = userService.getSeller(sellerId);
		double total = 0;
		if(cookies != null) {
		for(int i = 1;i < cookies.length;i++) {
			int foodId = Integer.valueOf(cookies[i].getName());
			int sum = Integer.valueOf(cookies[i].getValue());			
			Food food = userService.getFood(foodId);
			
			total += sum * food.getPrice();
			
			food.setSum(sum);
			foods.add(food);
		}
		}
		
		map.put("seller", seller);
		map.put("foods", foods);
		map.put("total", total);
		
		return map;
	}
	/**
	 * 在购物车里添加商品的数量
	 * @param request
	 * @param response
	 * @param foodId_
	 * @return Map<String,Object>
	 */
	@ResponseBody
	@RequestMapping(value = "/plusFoods/{foodId}",method = RequestMethod.POST)
	public Map<String,Object> plusFoods(HttpServletRequest request,HttpServletResponse response, @PathVariable("foodId") int foodId_){
		Map<String,Object> map = new HashMap<String, Object>();
		Cookie[] cookies = request.getCookies();
		String foodId = String.valueOf(foodId_);
		double total = 0;
		
		if(cookies == null) {
			
		}
		else {
			for(int i = 1;i < cookies.length;i++) {
				int foodId2 = Integer.valueOf(cookies[i].getName());
				int sum_ = Integer.valueOf(cookies[i].getValue());			
				Food food = userService.getFood(foodId2);				
				total += sum_ * food.getPrice();
				
				if(cookies[i].getName().equals(foodId)) {
					int sum = Integer.valueOf(cookies[i].getValue());
					++sum;
					cookies[i].setValue(String.valueOf(sum));
					cookies[i].setPath("/");
					response.addCookie(cookies[i]);      //覆盖原先的cookie即修改cookie
					total += food.getPrice();
				}
				
			}
			
		}
		map.put("result", 1);
		map.put("total", total);
		return map;
	}
	/**
	 * 在购物车里减少商品的数量
	 * @param request
	 * @param response
	 * @param foodId_
	 * @return Map<String,Object>
	 */
	@ResponseBody
	@RequestMapping(value = "/minusFoods/{foodId}",method = RequestMethod.POST)
	public Map<String,Object> minusFoods(HttpServletRequest request,HttpServletResponse response, @PathVariable("foodId") int foodId_){
		Map<String,Object> map = new HashMap<String, Object>();
		Cookie[] cookies = request.getCookies();
		String foodId = String.valueOf(foodId_);
		double total = 0;
		
		if(cookies == null) {
		
		}
		else {
			for(int i = 1;i < cookies.length;i++) {
				int foodId2 = Integer.valueOf(cookies[i].getName());
				int sum_ = Integer.valueOf(cookies[i].getValue());			
				Food food = userService.getFood(foodId2);				
				total += sum_ * food.getPrice();
				
				if(cookies[i].getName().equals(foodId)) {
					int sum = Integer.valueOf(cookies[i].getValue());
					if(sum <= 0) {
						cookies[i].setValue("0");
						cookies[i].setPath("/");        //必须配置路径，否则另一个方法不能获取到相同的cookie
						response.addCookie(cookies[i]);
						System.out.println(cookies[i].getName() + sum);
					}
					else {
					--sum;
					cookies[i].setValue(String.valueOf(sum));
					cookies[i].setPath("/");
					response.addCookie(cookies[i]);
					total -= food.getPrice();
					}
				}
			}
		}
		map.put("result", 1);
		map.put("total", total);
		
		return map;
	}
	/**
	 * 清空购物车
	 * @param request
	 * @param response
	 * @param foodId_
	 * @return Map<String,Object>
	 */
	@ResponseBody
	@RequestMapping(value = "/empty",method = RequestMethod.POST)
	public Map<String,Object> empty(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String, Object>();
		Cookie[] cookies = request.getCookies();
		
		double total = 0;
		
		if(cookies == null) {
		
		}
		else {
			for(int i = 0;i < cookies.length;i++) {
				cookies[i].setMaxAge(0);
			}
		}
		map.put("result", 1);
		map.put("total", total);
		
		return map;
	}
	/**
	 * 确认订单
	 * @param request
	 * @param response
	 * @param sellerId
	 * @return Map<String,Object>
	 */
	@ResponseBody
	@RequestMapping(value = "/confirm/{sellerId}",method = RequestMethod.GET)
	public Map<String,Object> confirm(HttpServletRequest request,HttpServletResponse response,@PathVariable("sellerId") int sellerId){
		Map<String,Object> map = new HashMap<String, Object>();
		Cookie[] cookies = request.getCookies();
		List<Food> foods = new ArrayList<Food>(); 
		
		Seller seller = userService.getSeller(sellerId);
		double total = 0;
		if(cookies != null) {
		for(int i = 1;i < cookies.length;i++) {
			int foodId = Integer.valueOf(cookies[i].getName());
			int sum = Integer.valueOf(cookies[i].getValue());			
			Food food = userService.getFood(foodId);
			
			total += sum * food.getPrice();
			
			food.setSum(sum);
			foods.add(food);
		}
		}
		
		map.put("seller", seller);
		map.put("foods", foods);
		map.put("total", total);
		
		return map;
	}
	/**
	 * 生成订单
	 * @param request
	 * @param response
	 * @param userId
	 * @return Map<String,Object>
	 * @throws ParseException 
	 */
	@ResponseBody
	@RequestMapping(value = "/order",method = RequestMethod.POST)
	public Map<String,Object> order(HttpServletRequest request,HttpServletResponse response,@RequestBody Order order) throws ParseException{
		Map<String,Object> map = new HashMap<String, Object>();
		Cookie[] cookies = request.getCookies();
		StringBuffer foods = null;
		
		int number = (int)(Math.random()*100);   //随机生成0-100数字
		
		Date day=new Date();           //获取生成订单时间
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		String date = df.format(day);  
		Date time = df.parse(date);
		
		if(cookies == null) {         //获取购物车的所有菜品
		
		}
		else {
			for(int i = 0;i < cookies.length;i++) {
				foods.append(cookies[i].getName());
				if(i < cookies.length-1)
					foods.append(",");				   
			}
		}
		
		order.setNumber(String.valueOf(number));
		order.setTime(time);
		order.setFoods(String.valueOf(foods));
		
		userService.addOrder(order);
		
		map.put("result", 1);
		
		return map;
	}
	
	
    
}  